package com.lins.framework.http.util;

import com.lins.framework.common.Constants;
import com.lins.framework.common.base.MyApplication;
import com.lins.framework.http.HttpResult;
import com.lins.framework.http.api.LinsApi;
import com.lins.framework.utils.tip.LogUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.functions.Func1;

/**
 * Created by Admin on 2017/3/14.
 */

public class Networks {
    private static final int DEFAULT_TIMEOUT = 30;

    private static Retrofit retrofit;

    private static Converter.Factory gsonConerterFactory = ResponseConvertFactory.create();

    private NetworkMonitor networkMonitor = new MyNetworkMonitor(MyApplication.getInstance().getApplicationContext());
    private static LinsApi mLinsApi;

    private static Networks mNetworks;

    public static Networks getInstance() {
        if (mNetworks == null) {
            mNetworks = new Networks();
        }
        return mNetworks;
    }

    public LinsApi getMApi() {
        return mLinsApi == null ? configRetrofit(LinsApi.class) : mLinsApi;
    }

    private <T> T configRetrofit(Class<T> service) {
        retrofit = new Retrofit.Builder()
                .baseUrl(Constants.APP_URL)
                .client(configClient())
                .addConverterFactory(gsonConerterFactory)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(service);
    }

    private OkHttpClient configClient() {
        //日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.HEADERS;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印请求头
                LogUtil.info(message);
//                Log.d(Constants.LOG_HEADER, message);
            }
        });
        loggingInterceptor.setLevel(level);

        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        if (networkMonitor.isConnected()) {
                            return chain.proceed(chain.request());
                        } else {
                            throw new ApiException("当前网络不可用，请检查网络情况");
                        }
                    }
                })
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        //TODO:添加http请求头，未经服务器测试
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("Source", "Android")
//                                .addHeader("User-Agent", "Lins")
                                .build();
                        return chain.proceed(request);
                    }
                })
                .addInterceptor(loggingInterceptor)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        return okHttpClient.build();
    }

    /**
     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T> Subscriber真正需要的数据类型，也就是Data部分的数据类型
     */
    public static class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {
        @Override
        public T call(HttpResult<T> httpResult) {
            if (httpResult.getStatus() != 1) {
                //错误码及错误提示信息
                throw new ApiException(httpResult.getMsg() + "\ncode:" + httpResult.getStatus());
            }
            return httpResult.getData();
        }
    }

    /**
     * 用来统一处理Http的resultCode,并统一处理Ret=104的返回状态
     */
    public static class HttpResultFunc2 implements Func1<HttpResult, HttpResult> {
        @Override
        public HttpResult call(HttpResult httpResult) {
            if (httpResult.getStatus() == 1) {
                //错误码及错误提示信息
                throw new ApiException(httpResult.getMsg());
            } else
                return httpResult;
        }
    }
}
